package com.qf.chinatrip;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.*;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import com.jakewharton.disklrucache.DiskLruCache;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qf.chinatrip.adapter.CommonFragmentAdapter;
import com.qf.chinatrip.fragment.DetailCommentFragment;
import com.qf.chinatrip.fragment.DetailJourneyFragment;
import com.qf.chinatrip.fragment.DetailMsgFragment;
import com.qf.chinatrip.model.ProductDetails;
import com.qf.chinatrip.utils.BitmapUtilsHelper;
import com.qf.chinatrip.utils.CommonUtils;
import com.qf.chinatrip.utils.NetUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;

/**
 * Created by Fcy on 2015/3/22.
 * 点击跳转查看详情的时候，必须intent传递 ProductId, systemType?
 */
public class DetailsActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener,
        RadioGroup.OnCheckedChangeListener {
    private static final String API_DETAILS = "http://m.springtour.com/home/appnewtour/detail";
    private LinearLayout layout;
    private ImageView preview;
    private TextView price;
    private TextView oldPrice;
    private TextView imgNum;
    private TextView type;
    private TextView title;
    private LinearLayout privilegeLayout;
    private TextView privilegeContent;
    private TextView from;
    private TextView to;
    private TextView time;
    private TextView contentName;
    private TextView content;
    private TextView order;
    private ViewPager viewPager;
    private RadioGroup tabGroup;
    private TextView code;
//    private Dialog dialog;

    private ProductDetails pro;
    private DiskLruCache cache;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);

        cache = initDiskCache(this);
        initView();

        Intent intent = getIntent();
        if (intent != null) {
            String id = intent.getStringExtra(Constans.KEY_INTENT_PRODUCT_ID);
            //detail?systemType=2&routeId=13623&orderFrom=5
            String url = API_DETAILS + "?systemType=2&routeId=" + id + "&orderFrom=5";
//        String url = "http://m.springtour.com/home/appnewtour/detail?systemType=2&routeId=13623&orderFrom=5";
            loadFromCache(url);

        }

    }

    /**
     * 1.初始化 DiskLruCache
     *
     * @param context
     * @return
     */
    public DiskLruCache initDiskCache(Context context) {
        DiskLruCache cache = null;
        // 1.初始化 DiskLruCache

        try {
            cache = DiskLruCache.open(
                    CommonUtils.getDiskCacheDir(context, "json"),
                    CommonUtils.getVersionCode(context), 1,
                    1024 * 1024 * 30);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return cache;
    }

    /**
     * Activity调用onCreate()方法时，先从缓存中加载数据
     *
     * @param url
     */
    public void loadFromCache(String url) {
        // 2.如果是 头数据 先从缓存中获取，再下载
        if (cache != null) {
            try {
                DiskLruCache.Snapshot snapshot = cache.get(
                        CommonUtils.urlMDToString(url));
                if (snapshot != null) {
                    String cacheStr = snapshot.getString(0);
                    // 使用缓存
                    CommonUtils.toast(this, "加载缓存");
                    // TODO 3.显示UI
                    show(url, cacheStr, true);
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        // 3.从网络加载，成功更新缓存
        loadData(url);

    }

    public void initView() {
        setTitle("产品详情");
//        dialog = CommonUtils.getProgressDialog(this, "正在加载...");

        layout = (LinearLayout) findViewById(R.id.details_content_block);

        preview = (ImageView) findViewById(R.id.goods_details_preview);
        preview.setOnClickListener(this);

        // 一键分享
        findViewById(R.id.goods_detail_share).setOnClickListener(this);

        code = (TextView) findViewById(R.id.goods_details_code);
        price = (TextView) findViewById(R.id.goods_details_price);
        oldPrice = (TextView) findViewById(R.id.goods_details_old_price);
        imgNum = (TextView) findViewById(R.id.goods_details_img_num);
        findViewById(R.id.goods_detail_consult).setOnClickListener(this);
        findViewById(R.id.goods_detail_comment).setOnClickListener(this);
        findViewById(R.id.goods_detail_share).setOnClickListener(this);

        type = (TextView) findViewById(R.id.goods_detail_type);
        title = (TextView) findViewById(R.id.goods_details_title);
        privilegeLayout = (LinearLayout) findViewById(R.id.goods_detail_privilege);
        privilegeContent = (TextView) findViewById(R.id.goods_detail_privilege_content);
        from = (TextView) findViewById(R.id.goods_detail_place_from);
        to = (TextView) findViewById(R.id.goods_detail_place_to);
        // 行程
        time = (TextView) findViewById(R.id.goods_detail_time);

        // “套餐内容”，可能是“班期”，还可能是“可选内容”，怎么区别“套餐”跟“班期”
        contentName = (TextView) findViewById(R.id.goods_details_content_name);
        content = (TextView) findViewById(R.id.goods_detail_content);
        order = (TextView) findViewById(R.id.goods_detail_order);

        // 三个Tab
        viewPager = (ViewPager) findViewById(R.id.goods_detail_pager);
        tabGroup = (RadioGroup) findViewById(R.id.goods_detail_tab_rg);
        tabGroup.setOnCheckedChangeListener(this);
//        RadioButton rbMsg = (RadioButton) tabGroup.getChildAt(0);
//        rbMsg.setChecked(true);

        // 立即预定
        findViewById(R.id.goods_details_reserve).setOnClickListener(this);
    }

    /**
     * 添加或更新缓存
     *
     * @param url
     * @param data
     */
    public void updateCache(String url, String data) {
        // 只缓存最新的数据
        if (cache != null) {
            try {
                DiskLruCache.Editor editor = cache.edit(CommonUtils.urlMDToString(url));
                // 写入缓存
                editor.set(0, data);
                // 必须调用 提交，否则无效
                editor.commit();
                CommonUtils.toast(this, "联网加载成功，更新缓存");

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void loadData(final String url) {
        if (!NetUtils.isConnected(this)) { // 未联网
            CommonUtils.toast(this, "请检查网络");
        } else {
            HttpUtils httpUtils = new HttpUtils(3000);
            httpUtils.configCurrentHttpCacheExpiry(0); // 缓存时间置零，有默认时间好像
            httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {

//                @Override
//                public void onStart() {
//                    dialog.show();
//                }

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String result = responseInfo.result;
                    show(url, result, false);

                }

                @Override
                public void onFailure(HttpException e, String s) {
                    CommonUtils.toast(DetailsActivity.this, "加载数据失败");
//                    dialog.dismiss();
                }
            });
        }

    }

    public void setUI() {
        // 显示“详情”界面
        layout.setVisibility(View.VISIBLE);
//        dialog.dismiss();

        // TODO 显示图库
        List<LinkedHashMap<String, String>> productPics = pro.getProductPics();
        imgNum.setText(productPics.size() + "张");
        // TODO 下载图片
        BitmapUtils bitmapUtils = BitmapUtilsHelper.initUtils(this, R.drawable.loading_normal);
        bitmapUtils.display(preview, pro.getImgSrc(), new BitmapLoadCallBack<ImageView>() {
            @Override
            public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap,
                                        BitmapDisplayConfig bitmapDisplayConfig,
                                        BitmapLoadFrom bitmapLoadFrom) {
                // 更改ImageView的ScaleType
                preview.setScaleType(ImageView.ScaleType.CENTER_CROP);
                preview.setImageBitmap(bitmap);
            }

            @Override
            public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {

            }
        });

        // TODO 显示ui
        // 编号
        String routeNo = pro.getRouteNo(); // 编号
        if (TextUtils.isEmpty(routeNo)) {
            code.setText("");
        } else {
            code.setText("编号【" + routeNo + "】");
        }

        // 设置原始价和现在价
        String orignPrice = pro.getOrignPrice();
        String startPrice = pro.getStartPrice();
        if (startPrice.equals(orignPrice)) {
            // 如果原始价与现在价格相等，则让原始价格不可见
            oldPrice.setVisibility(View.GONE);
        } else {
            price.setText("￥" + startPrice); // 现在价格
            // 设置原始价格，并且设置中划线并加清晰
            oldPrice.getPaint().setFlags(
                    Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            oldPrice.setText("￥" + orignPrice + "起");
        }

        // FIXME 处理“周边游”... 使用TextSpan
        type.setText(pro.getProductTypeName());
        title.setText(pro.getTitle());

        // “优惠”
        String recommend = pro.getRecommend();
        if (TextUtils.isEmpty(recommend)) {
            privilegeLayout.setVisibility(View.GONE);
        } else {
            privilegeContent.setText(recommend);
        }

        // “出发地”，“目的地”，“行程”信息
        from.setText(pro.getDepartCity());
        to.setText(pro.getDestination());
        time.setText(pro.getTravel());

        // FIXME “班期”或者是“可选内容”，或者是“套餐内容”，目前不知道如何区分“可选”和“套餐”
        String schedule = pro.getSchedule();
        content.setText(schedule);
        // 设置名称
        if (schedule.contains("日历")) {
            contentName.setText("班期");
        } else {
            contentName.setText("可选内容");
        }

        // “班次” //服务器数据格式 "2015-03-28": "253" 转换成03/28,保持服务器给的顺序
        StringBuffer sb = new StringBuffer();
        LinkedHashMap<String, String> routeScheduleDict = pro.getRouteScheduleDict();
        String s = routeScheduleDict.toString();
        // FIXME 为什么换做LinkedHashMap 还不对
        Log.i(">>", s);
        TreeSet<String> keySet = new TreeSet<String>(routeScheduleDict.keySet());
        for (String key : keySet) {
            // 2015-03-28 转换成 03/28
            String value = key.substring(5).replace("-", "/");
            sb.append(value).append("、");
        }

        order.setText(sb.toString());

        // TODO 3个tab
        //“基本信息”
        List<Fragment> fragments = new LinkedList<Fragment>();
        DetailMsgFragment msgFragment = new DetailMsgFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("product", pro);
        msgFragment.setArguments(bundle);
        fragments.add(msgFragment);

        // FIXME “行程”，传递 key。可能是“费用”，
        String travelDays = pro.getTravelDays();
        RadioButton rbMid = (RadioButton) tabGroup.getChildAt(2);
        rbMid.setText("行程（" + travelDays + "日）");
        DetailJourneyFragment journeyFragment = new DetailJourneyFragment();
        bundle = new Bundle();
        journeyFragment.setArguments(bundle);
        fragments.add(journeyFragment);


        // “点评”
        String commentCount = pro.getCommentCount();
        RadioButton rbComment = (RadioButton) tabGroup.getChildAt(4);
        if (commentCount.equals("0")) {
            // 没有点评，显示为“点评”
            rbComment.setText("点评");
        } else {
            rbComment.setText("点评（" + commentCount + "条）");
        }
        DetailCommentFragment commentFragment = new DetailCommentFragment();
        bundle = new Bundle();
        // FIXME
        commentFragment.setArguments(bundle);
        fragments.add(commentFragment);
        CommonFragmentAdapter adapter = new CommonFragmentAdapter(getSupportFragmentManager(), fragments);

        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(this);

        // TODO 解决ScrollView嵌套ViewPager显示不全无法滚动问题，必须在viewPage 设置setAdapter之后调用
        final int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        final int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        ViewTreeObserver observer = viewPager.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                viewPager.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);
                View view = viewPager.getChildAt(viewPager.getCurrentItem());
                view.measure(width, height);
                Log.i(">>", "width:" + width + ",height:" + height);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                params.height = view.getMeasuredHeight();

                viewPager.setLayoutParams(params);
            }
        });
    }

    public void show(String url, String result, boolean readFromCache) {
        // 解析
        try {
            JSONObject jsonObject = new JSONObject(result);
            boolean hasError = jsonObject.getBoolean("HasError");
            if (!hasError) { // 没有错误，解析
                JSONObject response = jsonObject.getJSONObject("Response");
                pro = new ProductDetails();
                pro.parseJson(response);
                // TODO 4.加载成功，则显示“详情”
                setUI();
                if (!readFromCache) { // 如果是联网下载的，更新缓存
                    // TODO 5.更新缓存
                    updateCache(url, result);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 一键分享
     *
     * @param context
     */
    private void showShare(Context context) {
        // !! 这个方法必须调用，用于初始化
        ShareSDK.initSDK(context);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字
        oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("春秋旅游分享");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用（在使用 QQ 和 QQ空间时必须设置这个）
        oks.setTitleUrl("http://m.springtour.com/tour/" + pro.getRouteId());

        //text是分享文本，所有平台都需要这个字段
        //http://m.springtour.com/tour/4505
        oks.setText(pro.getTitle() + "http://m.springtour.com/tour/" + pro.getRouteId());
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://m.springtour.com/tour/" + pro.getRouteId());
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("春秋旅游");
        oks.setImageUrl(pro.getImgSrc());

        // 启动分享GUI
        oks.show(context);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (pro == null) { // 不会为null，未加载成功时，界面是被隐藏的
            return;
        }

        Intent intent = null;
        switch (v.getId()) {
            case R.id.goods_details_preview:
                intent = new Intent(this, AlbumActivity.class);
                intent.putExtra("product", pro);
                break;
            case R.id.goods_detail_share: // 分享
                showShare(this);
                break;
        }

        if (intent != null) {
            startActivity(intent);
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int position) {
        RadioButton rb = (RadioButton) tabGroup.getChildAt(2 * position);
        rb.setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.goods_detail_tab_left:
                viewPager.setCurrentItem(0);
                break;
            case R.id.goods_detail_tab_mid:
                viewPager.setCurrentItem(1);
                break;
            case R.id.goods_detail_tab_right:
                viewPager.setCurrentItem(2);
                break;
        }
    }
}